package com.tinem.platform.web.gateway.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.tinem.platform.module.pojo.enums.common.Env;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className SwaggerController
 * @description TODO
 * @site
 * @company
 * @create 2021/12/3 12:00:12
 */
@RestController
@RequestMapping("/swagger/v2/")
public class SwaggerController {
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    RestTemplate restTemplate;

    List<JSONObject> allServices;

    @GetMapping("api-docs")
    public Object apiDocs(@RequestParam(required = false,name = "serviceName")String serviceName){
        if(StrUtil.isEmpty(serviceName)){
            if(allServices==null || allServices.size()==0){
                getAllServices();
            }
            return allServices;
        }else {
            ResponseEntity<JSONObject> res = restTemplate.getForEntity("http://"+serviceName+"/swagger/v2/api-docs", JSONObject.class);
            return res.getBody();
        }
    }
    @Scheduled(cron = "0 0/5 * * * ? ")
    public void getAllServices(){
        List<String> services = discoveryClient.getServices();
        this.allServices =services.stream().filter(service->{
            if(service.startsWith("platform-cloud-service")){
                return true;
            }
            if(service.startsWith("platform-cloud-business")){
                return true;
            }
            for (Env e: Env.values()) {
                if(service.startsWith(e.name()+"-platform-cloud-service")){
                    return true;
                }
                if(service.startsWith(e.name()+"-platform-cloud-business")){
                    return true;
                }
            }
            return false;
        }).map(service->{
            ResponseEntity<JSONObject> res = restTemplate.getForEntity("http://"+service+"/swagger/v2/api-docs", JSONObject.class);
            JSONObject jsonObject =  res.getBody();
            jsonObject.getJSONObject("info").put("title",service);
            return jsonObject;
        }).collect(Collectors.toList());
    }
}
